package com.wj.blog.realm;

import com.wj.blog.enums.ResultEnum;
import com.wj.blog.enums.StateEnums;
import com.wj.blog.excepition.BlogException;
import com.wj.blog.pojo.Admin;
import com.wj.blog.pojo.User;
import com.wj.blog.service.AdminService;
import com.wj.blog.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Author:   wj
 * Date:     2020/4/9 22:25
 * Description: 管理员登录和授权逻辑处理
 */
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;
    @Autowired
    private UserService userService;


    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return new SimpleAuthorizationInfo();
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        Admin admin = adminService.getByUsername(username);
        if (admin==null){
            throw new BlogException(ResultEnum.ERROR.getCode(),"用户不存在");
        }
        return new SimpleAuthenticationInfo(admin,admin.getPassword(),admin.getUsername());
    }
}
